<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="model-selector">
        <select v-model="selectedModelId" class="model-select" required>
          <option value="" disabled>选择模型</option>
          <option 
            v-for="model in models" 
            :key="model.id" 
            :value="model.id"
          >
            {{ model.name }}
          </option>
        </select>
        <router-link to="/settings" class="settings-link">⚙️</router-link>
      </div>
    </div>
    
    <div class="chat-messages" ref="messagesContainer">
      <div v-if="messages.length === 0" class="empty-state">
        <div class="empty-icon">💭</div>
        <p>开始新的对话</p>
      </div>
      <div v-else v-for="msg in messages" :key="msg.id" :class="['message', msg.role]">
        <div class="message-avatar">
          <img 
            :src="msg.role === 'user' ? userAvatar : botAvatar" 
            :alt="msg.role === 'user' ? '用户' : 'AI'"
          />
        </div>
        <div class="message-bubble">
          <div v-if="msg.role === 'assistant'">
            <div v-if="msg.reasoning" class="reasoning">
              <div class="reasoning-header">
                <span class="reasoning-icon">🤔</span>
                思考过程
              </div>
              <div class="reasoning-content" v-html="renderMarkdown(msg.reasoning)"></div>
            </div>
            <div v-html="renderMarkdown(msg.content)"></div>
            <div v-if="msg.loading" class="loading-dots">
              <span></span><span></span><span></span>
            </div>
          </div>
          <div v-else>{{ msg.content }}</div>
        </div>
      </div>
    </div>

    <div class="chat-input-container">
      <div class="input-wrapper">
        <textarea 
          v-model="inputMessage" 
          @keydown.enter.prevent="sendMessage"
          placeholder="输入消息..."
          :disabled="!selectedModelId || isLoading"
          rows="1"
          ref="inputArea"
          @input="adjustTextareaHeight"
        ></textarea>
        <button 
          @click="sendMessage" 
          :disabled="!selectedModelId || isLoading || !inputMessage.trim()"
          class="send-button"
        >
          <span v-if="isLoading">
            <span class="loading-spinner"></span>
          </span>
          <span v-else>发送</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, onUnmounted } from 'vue'
import type { AIModel } from '@/types/model'
import  { getModels, getDefaultModel } from '@/utils/request'
import MarkdownIt from 'markdown-it'
import { promptStorage } from '@/utils/promptStorage'
import { chatStorage, type ChatSession } from '@/utils/chatStorage'
import type { TokenStats } from '@/types/chat'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'

interface ChatMessage {
  id: number
  role: 'user' | 'assistant'
  content: string
  reasoning?: string
  loading?: boolean
  tokenStats?: TokenStats
}

const models = ref<AIModel[]>([])
const selectedModelId = ref<number>()
const inputMessage = ref('')
const messages = ref<ChatMessage[]>([])
const isLoading = ref(false)

const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true,
  highlight: function (str: string, lang: string): string {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs" data-lang="${lang}"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`
      } catch (__) {}
    }
    return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`
  }
})

const renderMarkdown = (content: string) => {
  return md.render(content)
}

onMounted(async () => {
  try {
    // 1. 先获取所有模型列表
    const modelsRes = await getModels()
    if (modelsRes.data) {
      models.value = modelsRes.data.map((model: any) => ({
        id: model.id,
        name: model.name,
        model: model.model,
        baseUrl: model.base_url,
        apiKey: model.api_key,
        isDefault: Boolean(model.is_default)
      }))
    }

    // 2. 获取默认模型
    const defaultRes = await getDefaultModel()
    if (defaultRes.data) {
      selectedModelId.value = defaultRes.data.id
    }

    // 添加事件监听器
    window.addEventListener('load-chat-session', ((event: CustomEvent<ChatSession>) => {
      loadSession(event.detail)
    }) as EventListener)

    // 监听开启新对话事件
    window.addEventListener('start-new-chat', () => {
      clearChat()
    })
  } catch (error) {
    console.error('获取模型列表失败:', error)
  }
})

// 监听模型变化
watch(() => models.value, async () => {
  // 如果当前没有选中的模型，尝试获取默认模型
  if (!selectedModelId.value) {
    try {
      const defaultRes = await getDefaultModel()
      if (defaultRes.data) {
        selectedModelId.value = defaultRes.data.id
      }
    } catch (error) {
      console.error('获取默认模型失败:', error)
    }
  }
}, { deep: true })

// 获取当前选中的模型
const getCurrentModel = () => {
  return models.value.find(m => m.id === selectedModelId.value)
}

const handleStreamComplete = (json: any, lastMessage: ChatMessage) => {
  if (json.usage) {
    lastMessage.tokenStats = {
      promptTokens: json.usage.prompt_tokens,
      completionTokens: json.usage.completion_tokens,
      totalTokens: json.usage.total_tokens
    }
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || !selectedModelId.value) return
  
  const currentModel = getCurrentModel()
  if (!currentModel) return

  const userMessage: ChatMessage = {
    id: Date.now(),
    role: 'user' as const,
    content: inputMessage.value.trim()
  }

  const assistantMessage: ChatMessage = {
    id: Date.now() + 1,
    role: 'assistant' as const,
    content: '',
    loading: true
  }

  messages.value.push(userMessage)
  messages.value.push(assistantMessage)
  inputMessage.value = ''
  isLoading.value = true

  try {
    const defaultPrompt = promptStorage.getDefaultPrompt()
    const messageHistory = [
      ...(defaultPrompt ? [{
        role: 'system',
        content: defaultPrompt.content
      }] : []),
      ...messages.value
        .filter(msg => !msg.loading)
        .map(msg => ({
          role: msg.role,
          content: msg.content
        }))
    ]

    const apiUrl = currentModel.baseUrl.endsWith('/')
      ? `${currentModel.baseUrl}chat/completions`
      : `${currentModel.baseUrl}/chat/completions`

    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${currentModel.apiKey}`
      },
      body: JSON.stringify({
        model: currentModel.model,
        messages: messageHistory,
        temperature: 0.7,
        max_tokens: 2000,
        stream: true
      })
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
    }

    const reader = response.body?.getReader()
    const decoder = new TextDecoder()

    if (!reader) throw new Error('无法获取响应流')

    while (true) {
      const { done, value } = await reader.read()
      if (done) {
        const response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${currentModel.apiKey}`
          },
          body: JSON.stringify({
            model: currentModel.model,
            messages: messageHistory,
            temperature: 0.7,
            max_tokens: 2000,
            stream: false
          })
        })
        
        if (response.ok) {
          const json = await response.json()
          const lastMessage = messages.value[messages.value.length - 1]
          if (lastMessage && lastMessage.role === 'assistant') {
            handleStreamComplete(json, lastMessage)
          }
        }
        break
      }

      const chunk = decoder.decode(value)
      const lines = chunk
        .split('\n')
        .filter(line => line.trim() !== '' && line.trim() !== 'data: [DONE]')

      for (const line of lines) {
        try {
          const jsonStr = line.replace(/^data: /, '').trim()
          if (!jsonStr) continue

          const json = JSON.parse(jsonStr)
          const content = json.choices[0]?.delta?.content || ''
          const reasoning = json.choices[0]?.delta?.reasoning_content || ''
          
          const lastMessage = messages.value[messages.value.length - 1]
          if (lastMessage && lastMessage.role === 'assistant') {
            if (reasoning) {
              lastMessage.reasoning = (lastMessage.reasoning || '') + reasoning
            }
            if (content) {
              lastMessage.content = (lastMessage.content || '') + content
            }
          }
        } catch (e) {
          console.error('Error parsing SSE message:', e)
        }
      }
    }

    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && lastMessage.role === 'assistant') {
      lastMessage.loading = false
    }
  } catch (error) {
    console.error('API调用失败:', error)
    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && lastMessage.role === 'assistant') {
      lastMessage.content = `错误：${error instanceof Error ? error.message : '请求失败，请检查API配置或网络连接'}`
      lastMessage.loading = false
    }
  } finally {
    isLoading.value = false
  }
}

// 添加自动调整文本框高度的方法
const inputArea = ref<HTMLTextAreaElement>()
const messagesContainer = ref<HTMLDivElement>()

const adjustTextareaHeight = () => {
  if (!inputArea.value) return
  inputArea.value.style.height = 'auto'
  inputArea.value.style.height = `${Math.min(inputArea.value.scrollHeight, 150)}px`
}

// 在消息发送后滚动到底部
const scrollToBottom = () => {
  if (!messagesContainer.value) return
  messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
}

// 监听消息变化，自动滚动
watch(() => messages.value, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 保存会话
const saveSession = () => {
  if (messages.value.length === 0) return
  
  const currentModel = getCurrentModel()
  if (!currentModel) return

  const title = messages.value[0].content.slice(0, 50) + '...'
  chatStorage.saveSession({
    title,
    messages: messages.value,
    modelId: currentModel.id
  })
}

// 加载会话
const loadSession = (session: ChatSession) => {
  messages.value = session.messages
  selectedModelId.value = session.modelId
}

// 在消息发送成功后保存会话
watch(() => messages.value, () => {
  if (messages.value.length > 0 && !isLoading.value) {
    saveSession()
  }
}, { deep: true })

// 清空对话
const clearChat = () => {
  messages.value = []
}

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('load-chat-session', ((event: CustomEvent<ChatSession>) => {
    loadSession(event.detail)
  }) as EventListener)
  window.removeEventListener('start-new-chat', () => {
    clearChat()
  })
})

// 添加头像
const userAvatar = 'https://q1.qlogo.cn/g?b=qq&nk=7097341&s=100'
const botAvatar = '/ai-avatar.png' // 需要添加一个AI头像
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
}

.chat-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 0.75rem 1rem;
  background: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.model-selector {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding-left: 3rem; /* 为菜单按钮留出空间 */
}

.model-select {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
  font-size: 0.875rem;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  padding-top: 4rem; /* 为固定header留出空间 */
  padding-bottom: 5rem; /* 为输入框留出空间 */
}

.message {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 1rem;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 2.5rem;
  height: 2.5rem;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.message-bubble {
  max-width: 70%;
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  font-size: 0.9375rem;
  line-height: 1.5;
}

.message.assistant .message-bubble {
  background: white;
  border-top-left-radius: 0.25rem;
}

.message.user .message-bubble {
  background: #95ec69;
  border-top-right-radius: 0.25rem;
}

.chat-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0.75rem 1rem;
  background: white;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
}

.input-wrapper {
  display: flex;
  gap: 0.75rem;
  background: #f3f4f6;
  border-radius: 1.25rem;
  padding: 0.5rem;
}

textarea {
  flex: 1;
  border: none;
  background: transparent;
  padding: 0.5rem;
  resize: none;
  max-height: 120px;
  font-size: 0.9375rem;
}

textarea:focus {
  outline: none;
}

.send-button {
  background: #07c160;
  color: white;
  border: none;
  border-radius: 1rem;
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
  cursor: pointer;
}

.send-button:disabled {
  background: #a8a8a8;
}

.empty-state {
  text-align: center;
  color: #6b7280;
  padding: 2rem;
}

.empty-icon {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.loading-dots span {
  display: inline-block;
  width: 0.5rem;
  height: 0.5rem;
  background: #d1d5db;
  border-radius: 50%;
  margin: 0 0.25rem;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

/* 代码块样式 */
:deep(pre) {
  margin: 0.5rem 0;
  padding: 1rem;
  background: #1f2937;
  border-radius: 0.5rem;
  overflow-x: auto;
}

:deep(code) {
  font-size: 0.875rem;
  line-height: 1.5;
}

/* PC端适配 */
@media (min-width: 769px) {
  .chat-container {
    max-width: 1000px;
    margin: 0 auto;
    height: calc(100vh - 2rem);
    margin-top: 1rem;
    border-radius: 1rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  }

  .chat-header {
    position: relative;
    border-radius: 1rem 1rem 0 0;
    padding: 1rem 2rem;
  }

  .model-selector {
    max-width: 400px;
    margin: 0 auto;
    padding-left: 0;
  }

  .chat-messages {
    padding: 2rem;
    padding-top: 1rem;
    padding-bottom: 7rem;
  }

  .message-bubble {
    max-width: 60%;
    padding: 1rem 1.5rem;
  }

  .message-avatar {
    width: 3rem;
    height: 3rem;
  }

  .chat-input-container {
    max-width: 1000px;
    margin: 0 auto;
    border-radius: 0 0 1rem 1rem;
    padding: 1.5rem 2rem;
  }

  .input-wrapper {
    max-width: 800px;
    margin: 0 auto;
    padding: 0.75rem 1rem;
  }

  textarea {
    padding: 0.75rem;
    font-size: 1rem;
  }

  .send-button {
    padding: 0.75rem 1.5rem;
    font-size: 1rem;
  }

  /* 代码块在PC端的样式 */
  :deep(pre) {
    padding: 1.5rem;
    margin: 1rem 0;
  }

  :deep(code) {
    font-size: 1rem;
  }
}

/* 移动端样式保持不变 */
@media (max-width: 768px) {
  .chat-container {
    height: 100vh;
  }

  .chat-messages {
    padding: 1rem;
    padding-top: 4rem;
    padding-bottom: 5rem;
  }

  .message-bubble {
    max-width: 75%;
  }
}
</style> 